package com.credithc.eagleeye.plugins.httpclient;
import com.credithc.eagleeye.thread.EagleEyeThreadContext;
import com.credithc.eagleeye.thread.TraceInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;

import static com.credithc.eagleeye.constants.EagleEyeConstant.HC_RPC_ID;
import static com.credithc.eagleeye.constants.EagleEyeConstant.HC_TRACE_ID;
/**
 * 描 述: 仅仅传播traceId使用，比如不使用EagleEyeHttpClientBuilder<br/>
 * 作 者: zhangjin<br/>
 * 创 建：2019年10月28日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Slf4j
public class EagleEyeHttpClientRequestInterceptor implements HttpRequestInterceptor {
    @Override
    public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
        if (!request.containsHeader(HC_TRACE_ID)) {
            TraceInfo traceInfo = EagleEyeThreadContext.getTraceInfo();
            if (traceInfo == null) {
                traceInfo = new TraceInfo();
                EagleEyeThreadContext.init();
                EagleEyeThreadContext.putTraceInfo(traceInfo);
            }
            request.addHeader(HC_TRACE_ID,traceInfo.getTraceId());
            request.addHeader(HC_RPC_ID,traceInfo.getRpcId());
        }
    }
}
